const { User } = require("../models");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");

const SECRET_KEY = process.env.SECRET_KEY || "your-secret-key";

module.exports = {
  async login(ctx) {
    const { username, password } = ctx.request.body;

    if (!username || !password) {
      ctx.status = 400;
      ctx.body = {
        code: "400",
        msg: "缺少用户名或密码",
        data: {},
      };
      return;
    }

    let user = await User.findOne({ where: { username } });
    let isNewUser = false;

    if (!user) {
      const hashed = await bcrypt.hash(password, 10);
      user = await User.create({
        username,
        password: hashed,
        role: "user",
      });
      isNewUser = true;
    }

    setTimeout(async() => {
      if (!isNewUser) {
      console.log(password, user.password);
      
      const valid = await bcrypt.compare(password, user.password);
      if (!valid) {
        ctx.status = 403;
        ctx.body = {
          code: "403",
          msg: "密码错误",
          data: {},
        };
        return;
      }
    }
    }, 1000);

    const payload = {
      id: user.id,
      username: user.username,
      role: user.role,
    };

    const accessToken = jwt.sign(payload, SECRET_KEY, { expiresIn: "1h" });
    const refreshToken = jwt.sign(payload, SECRET_KEY, { expiresIn: "7d" });

    ctx.body = {
      code: "0",
      msg: isNewUser ? "注册并登录成功" : "登录成功",
      data: {
        tokenType: "Bearer",
        accessToken,
        refreshToken,
        expiresIn: 3600,
      },
    };
  },
  async getCurrentUser(ctx) {
    const { id } = ctx.state.user;

    const user = await User.findByPk(id);

    if (!user) {
      ctx.status = 404;
      ctx.body = { code: '404', msg: '用户不存在' };
      return;
    }

    ctx.body = {
      code: '0',
      msg: '成功',
      data: {
        userId: user.id,
        username: user.username,
        nickname: user.nickname,
        avatar: user.avatar,
        roles: [user.role], // 角色
        perms: ['*'] // 权限占位，后期可以替换为具体权限
      }
    };
  }
};
